# -*- coding: utf-8 -*- 
 
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.template import RequestContext
from django.core.urlresolvers import reverse 
from django.utils.http import urlquote 
from django.template import loader

import logging


def login_required(func):
    def decorate(request, *args, **kwargs):
        if 'auth' in request.session:
            ret = func(request, *args, **kwargs)
        else:
            path = urlquote(request.get_full_path()) 
            ret = HttpResponseRedirect('%s?next=%s' % (reverse('usuario.login'), path)) 
        return ret 
    return decorate 


def superuser_required(func):
    def decorate(request, *args, **kwargs):
        if 'auth' in request.session:
            if request.user.superusuario:
                ret = func(request, *args, **kwargs)
            else:
                log = logging.getLogger('usuarios.decorators.superuser_required')
                log.warn(u'%s tentando acessar %s.%s: Permissão negada por não ser superusuário.' % (request.user.usuario, func.__module__, func.__name__))
                ret = HttpResponseForbidden(loader.render_to_string('usuarios/forbidden.html', context_instance=RequestContext(request)))
        else:
            path = urlquote(request.get_full_path()) 
            ret = HttpResponseRedirect('%s?next=%s' % (reverse('usuario.login'), path)) 
        return ret 
    return decorate 


def permission_required(actions):
    def wrapper(func):
        def decorate(request, *args, **kwargs):
            if 'auth' in request.session:
                if request.user.tem_permissao(actions):
                    ret = func(request, *args, **kwargs)
                else:
                    log = logging.getLogger('usuarios.decorators.permission_required')
                    log.warn(u'%s tentando acessar %s.%s: Permissão negada por não ter "%s".' % (request.user.usuario, func.__module__, func.__name__, actions))
                    ret = HttpResponseForbidden(loader.render_to_string('usuarios/forbidden.html', context_instance=RequestContext(request)))
            else:
                path = urlquote(request.get_full_path()) 
                ret = HttpResponseRedirect('%s?next=%s' % (reverse('usuario.login'), path)) 
            return ret
        return decorate
    return wrapper


